import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:uuid/uuid.dart';

import 'flutter_websocket_platform_interface.dart';

/// An implementation of [FlutterWebsocketPlatform] that uses method channels.
class MethodChannelFlutterWebsocket extends FlutterWebsocketPlatform {
  /// The method channel used to interact with the native platform.
  @visibleForTesting
  final methodChannel = const MethodChannel('ext.plugin/flutter_websocket');

  final Uuid _uuid = const Uuid();

  @override
  Future<String> create(Uri uri) async {
    final id = _uuid.v4();
    return await methodChannel
        .invokeMethod('create', {'id': id, 'url': uri.toString()});
  }

  @override
  Future<void> connect(String id) => methodChannel.invokeMethod('connect', id);

  @override
  Stream eventFor(String id) => _eventChannelFor(id).receiveBroadcastStream();

  @override
  Future<void> send(String id, List<int> data) =>
      methodChannel.invokeMethod('send', {'id': id, 'data': data});

  @override
  Future<void> sendText(String id, String text) =>
      methodChannel.invokeMethod('sendText', {'id': id, 'text': text});

  @override
  Future<void> close(String id) => methodChannel.invokeMethod('close', id);

  EventChannel _eventChannelFor(String id) =>
      EventChannel('ext.plugin/websocketEvents$id');
}
